<?php

namespace UserAjax\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use UserAjax\Form\FormLogin;
use UserAjax\Form\FormRegister;
use UserAjax\Form\FilterFormLogin;
use UserAjax\Form\FilterFormRegister;
use Library\String;

class UserController extends AbstractActionController {

    private $objView;
    private $userModel;

    public function __construct() {
        $this->objView = new ViewModel();
    }

    public function loginAction() {

        $isAsyncRequest = $this->getRequest()->isXmlHttpRequest();

        $this->objView->setTerminal($isAsyncRequest);

        $session = new \Zend\Session\Container('member');

        if ($session->offsetExists('member_id')) {
            $this->redirect()->toRoute('product-ajax');
        }

        $formLogin = new FormLogin();

        $request = $this->getRequest();

        if ($request->isPost()) {

            $formLogin->setInputFilter(new FilterFormLogin());

            $formLogin->setData($request->getPost()->toArray());

            if ($formLogin->isValid()) {

                $userData = $formLogin->getData();

                $adapter = $this->getUserModel()->getAdapter();

                $authAdapter = new \Zend\Authentication\Adapter\DbTable($adapter, $this->getUserModel()->getTableMemberName(), 'member_email', 'member_password');

                $authAdapter->setIdentity($userData['member_email']);

                $authAdapter->setCredential(String::createPassword($userData['member_password']));

                $authAdapter->getDbSelect()->where(array('member_active' => 1));

                $authService = new \Zend\Authentication\AuthenticationService();

                $result = $authService->authenticate($authAdapter);

                if ($result->isValid()) {
                    //get data to create session
                    $aryUserSession = $authAdapter->getResultRowObject(array('member_id', 'member_email'));
                    //create session
                    $session->offsetSet('member_id', $aryUserSession->member_id);
                    $session->offsetSet('member_email', $aryUserSession->member_email);
                    if ($userData['remember_me'] == 1) {
                        $sessionManager = new \Zend\Session\SessionManager();
                        $sessionManager->rememberMe(302400);
                    }
                    $this->objView->setTemplate('user-ajax/login-success');
                    return $this->objView;
                } else {
                    $this->objView->setVariable('message', 'Email hoặc mật khẩu không đúng hoặc tài khoản chưa kích hoạt');
                }
            }
        }
        $this->objView->setVariable('formLogin', $formLogin);

        $this->objView->setTemplate('user-ajax/_login');

        return $this->objView;
    }

    public function loginSuccessAction() {

        $this->objView->setTemplate('user-ajax/login-success');
        return $this->objView;
    }

    public function logoutAction() {
        $sessionManager = new \Zend\Session\SessionManager();
        $sessionManager->forgetMe();
        $userSession = new \Zend\Session\Container('member');
        $userSession->getManager()->destroy();
        $this->redirect()->toRoute('ajax-user-login');
    }

    public function registerAction() {

        $isAsyncRequest = $this->getRequest()->isXmlHttpRequest();

        $this->objView->setTerminal($isAsyncRequest);

        $session = new \Zend\Session\Container('member');

        if ($session->offsetExists('member_id')) {
            $this->redirect()->toRoute('product-ajax');
        }

        $config = $this->getServiceLocator()->get('config');

        if ($config['mail_config']['connection_config']['username'] == '') {
            $this->objView->setVariable('noMailConfig', ' - Bạn chưa cấu hình mail trong file /config/mail.config.global.php');
        }

        $formRegister = new FormRegister();

        $request = $this->getRequest();

        if ($request->isPost()) {

            $data = $request->getPost()->toArray();

            $formRegister->setInputFilter(new FilterFormRegister());

            $noRecordExist = new \Zend\Validator\Db\NoRecordExists(array(
                'table' => $this->getUserModel()->getTableMemberName(),
                'field' => 'member_email',
                'adapter' => $this->getUserModel()->getAdapter(),
                'messages' => array(
                    \Zend\Validator\Db\NoRecordExists::ERROR_RECORD_FOUND => 'Email đã được đăng ký'
                )
            ));

            $formRegister->getInputFilter()->get('member_email')->getValidatorChain()->addValidator($noRecordExist);

            $formRegister->setData($data);

            if ($formRegister->isValid()) {

                $userData = $formRegister->getData();

                $aryResult = $this->getUserModel()->registerUser($userData);

                if ($aryResult['isOk'] == 1) {
                    $this->_sendEmailConfirm($aryResult['user_data']);
                    $this->objView->setVariable('userEmail', $aryResult['user_data']['member_email']);
                    $this->objView->setTemplate('user-ajax/_register_success');
                    return $this->objView;
                }
            }
        }

        $this->objView->setVariable('formRegister', $formRegister);

        $this->objView->setTemplate('user-ajax/_register');

        return $this->objView;
    }

    public function registerSuccessAction() {

        $this->objView->setTerminal(true);

        $userEmail = $this->flashMessenger()->getSuccessMessages();

        $this->objView->setVariable('userEmail', $userEmail[0]);

        $this->flashMessenger()->clearMessages();

        $this->objView->setTemplate('user-ajax/_register_success');

        return $this->objView;
    }

    public function _sendEmailConfirm($userData) {

        $render = $this->getServiceLocator()->get('Zend\View\Renderer\RendererInterface');

        $mailTemplate = $render->render('user/mail-template', array('token' => $userData['member_token']));

        $html = new \Zend\Mime\Part($mailTemplate);
        $html->type = 'text/html';
        $html->charset = 'UTF-8';

        $mailBody = new \Zend\Mime\Message();
        $mailBody->setParts(array($html));

        $objMessage = new \Zend\Mail\Message();
        $objMessage->setEncoding("UTF-8");
        $objMessage->addFrom('Zendpro.vn');
        $objMessage->addTo($userData['member_email']);
        $objMessage->setSubject('Kích hoạt tài khoản');
        $objMessage->setBody($mailBody);

        $config = $this->getServiceLocator()->get('config');

        $mailConfig = $config['mail_config'];

        $objSmtpOptions = new \Zend\Mail\Transport\SmtpOptions($mailConfig);

        $smtpTransport = new \Zend\Mail\Transport\Smtp();
        $smtpTransport->setOptions($objSmtpOptions);
        $smtpTransport->send($objMessage);
    }

    public function confirmEmailAction() {
        $token = $this->params()->fromRoute('token');
        $result = $this->getUserModel()->checkUserByToken($token);
        if ($result) {
            $result = $this->getUserModel()->activeUser($token);
            if ($result) {
                $this->redirect()->toRoute('ajax-confirm-success');
            }
        } else {
            $this->redirect()->toRoute('ajax-confirm-error');
        }
    }

    public function confirmSuccessAction() {

        $this->objView->setTemplate('user-ajax/confirm-success');
        return $this->objView;
    }

    public function confirmErrorAction() {
        $this->objView->setTemplate('user-ajax/confirm-error');
        return $this->objView;
    }

    public function testSendMailAction() {

        $render = $this->getServiceLocator()->get('Zend\View\Renderer\RendererInterface');

        $token = 'fsfasdfhdfgdfsgdfgdfg';

        $mailTemplate = $render->render('user/mail-template', array('token' => $token));

        $html = new \Zend\Mime\Part($mailTemplate);
        $html->type = 'text/html';
        $html->charset = 'UTF-8';

        $mailBody = new \Zend\Mime\Message();
        $mailBody->setParts(array($html));

        $objMessage = new \Zend\Mail\Message();
        $objMessage->setEncoding("UTF-8");
        $objMessage->addFrom('Zendpro.vn');
        $objMessage->addTo('gasphucyen@gmail.com');
        $objMessage->setSubject('Kích hoạt tài khoản');
        $objMessage->setBody($mailBody);

        $config = $this->getServiceLocator()->get('config');

        $mailConfig = $config['mail_config'];

        $objSmtpOptions = new \Zend\Mail\Transport\SmtpOptions($mailConfig);
//        $objSmtpOptions->setName('Localhost');
//        $objSmtpOptions->setHost('smtp.gmail.com');
//        $objSmtpOptions->setPort('587'); //465 for SSL : 587 for TLS
//        $objSmtpOptions->setConnectionClass('login');
//        $objSmtpOptions->setConnectionConfig(array(
//            'username' => 'manhcuongcn85@gmail.com',
//            'password' => 'manhcuongbvh',
//            'ssl' => 'tls',
//        ));

        $smtpTransport = new \Zend\Mail\Transport\Smtp();
        $smtpTransport->setOptions($objSmtpOptions);
        $smtpTransport->send($objMessage);

        echo 'send mail';
        exit();
    }

    public function getUserModel() {
        if (!$this->userModel) {
            $this->userModel = $this->getServiceLocator()->get('AjaxUserModel');
        }
        return $this->userModel;
    }

}
